import Taro from "@tarojs/taro";
import wx from './weixin-js-sdk/index'
/*
 * fun [function] 需要防抖的函数
 * delay [number] 毫秒，防抖期限值
 */
function debounce(fun, delay = 300) {
  let timer;
  return function () {
    let ctx = this
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      timer = null
      fun.apply(ctx, args)
    }, delay)
  }
}
/*
 * fun [function] 需要节流的函数
 * delay [number] 毫秒，节流期限值
 */
function throttle(handler, wait = 300) {
  let lastTime = 0;
  return function (e) {
    let nowTime = new Date().getTime();
    if (nowTime - lastTime > wait) {
        handler.apply(this, arguments);
        lastTime = nowTime;
    }
  }
}
//   显示消息框
function toast(str,icon = 'none',delay = 1500){
  Taro.showToast({
    title: str,
    icon,
    duration: delay,
    mask: true
  });
}

/*
 * num [function] 传入的数字
 * decimal [number] 需要保留几位小数
 */
function RoundNum(num, decimal = 2) {
	return Math.round(num * 10 ** decimal) / 10 ** decimal;
}
//  获取url上的参数
function getUrlParam(sUrl,sKey) {
    var sHref = sUrl || location.href;
    var args = sHref.split('?');
    if (args[0] === sHref) {
        return '';
    }
    var hrefarr = args[1].split('#')[0].split('&');
    var obj = {};
    for (var i = 0; i < hrefarr.length; i++) {
        hrefarr[i] = hrefarr[i].split('=');
        obj[hrefarr[i][0]] = hrefarr[i][1];
    }
    if (!sKey) {
        return obj;
    } else {
        return obj[sKey] || '';
    }
}

// 输入一个值，返回其数据类型**
function typeFta(para) {
    return Object.prototype.toString.call(para)
}

// 深克隆（深克隆不考虑函数）
function deepClone(obj, result) {
    var result = result || {};
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (typeof obj[prop] == 'object' && obj[prop] !== null) {
                // 引用值(obj/array)且不为null
                if (Object.prototype.toString.call(obj[prop]) == '[object Object]') {
                    // 对象
                    result[prop] = {};
                } else {
                    // 数组
                    result[prop] = [];
                }
                deepClone(obj[prop], result[prop])
    } else {
        // 原始值或func
        result[prop] = obj[prop]
    }
  }
}
return result;
}

function fVailPhone(thisElement) {
  var phone = thisElement;
  var flag = false;
  var message = "";
  var myreg = /^((0|86|17951)?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8})$/;
  if (!phone) {
      message = "手机号不能为空！";
  } else if (phone.length != 11) {
      message = "请输入有效的手机号码！";
  } else if (!myreg.test(phone)) {
      message = "请输入有效的手机号码！";
  } else {
      flag = true;
      message = "";
  }
  if (!flag) {
      Taro.showToast({
        title:message,
        icon:'none'
      })
  } else {
      // 操作成功
  }
  return flag;
}

/*
 * date [number] 时间戳或者时间标准
 * fmt [string] 时间格式
 */
function format(date, fmt = 'YYYY-MM-DD') {

	let newDate = date;
	let fmts = fmt;

	//fmts='YYYY-MM-DD HH:mm:ss'
	if (!newDate) {
		newDate = new Date;
	}
	if (typeof newDate === 'number') {
		newDate = new Date(newDate);
	}
	const o = {
		'M+': newDate.getMonth() + 1,
		'D+': newDate.getDate(),
		'h+': newDate.getHours() % 12 === 0 ? 12 : newDate.getHours() % 12,
		'H+': newDate.getHours(),
		'm+': newDate.getMinutes(),
		's+': newDate.getSeconds(),
		'q+': Math.floor((newDate.getMonth() + 3) / 3),
		S: newDate.getMilliseconds(),
	};
	const week = {
		0: '\u65e5',
		1: '\u4e00',
		2: '\u4e8c',
		3: '\u4e09',
		4: '\u56db',
		5: '\u4e94',
		6: '\u516d',
	};
	if (/(Y+)/.test(fmts)) {
		fmts = fmts.replace(RegExp.$1, (`${newDate.getFullYear()}`).substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmts)) {
		fmts = fmts.replace(RegExp.$1, () => {
			if (RegExp.$1.length > 1) {
				if (RegExp.$1.length > 2) {
					return `\u661f\u671f${week[newDate.getDay()]}`;
				}
				return `\u5468${week[newDate.getDay()]}`;
			}
			return week[`${newDate.getDay()}`];
		});
	}
	Object.keys(o).forEach((k) => {
		if (new RegExp(`(${k})`).test(fmts)) {
			fmts = fmts.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)));
		}
	});
	return fmts;
};

function whichPlatform() {
  //平台、设备和操作系统
  let system = {
    win: false,
    mac: false,
    xll: false,
    ipad: false
  };
  //检测平台
  let p = navigator.platform;
  system.win = p.indexOf("Win") == 0;
  system.mac = p.indexOf("Mac") == 0;
  system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
  system.ipad = (navigator.userAgent.match(/iPad/i) != null) ? true : false;
  let ua = navigator.userAgent.toLowerCase();
  //跳转语句，如果是手机访问就自动跳转到wap.baidu.com页面
  if (system.win || system.mac || system.xll || system.ipad) {
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return 2; ///"在PC端微信上打开的"
    } else {
      return 3; // "在PC端非微信上打开的"
    }
  } else {
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return 1;  // "在手机端微信上打开的"
    } else {
      return 4; //"在手机端微信上打开的"
    }
  }
}

function queryURLParams(URL) {
  let url = ''
  let obj = {}; // 声明参数对象
  // 使用indexOf()找到第一个问号的索引
  const firstQuestionMarkIndex = URL.indexOf('?');
  if (firstQuestionMarkIndex !== -1) {
    url = URL.slice(firstQuestionMarkIndex + 1);
  }
  let arr = url.split("&"); // 以&符号分割为数组
  for (let i = 0; i < arr.length; i++) {
    const firstIndex = arr[i].indexOf('=');
    if (firstIndex !== -1) {
      const firstPart = arr[i].slice(0, firstIndex);
      const secondPart = arr[i].slice(firstIndex + 1);
      obj[firstPart] = secondPart;
    }
  }
  return obj;
}
  
function checkSalesMan(opt){  //// 处理分销逻辑
  Taro.removeStorageSync('salesMan')
  if(opt.salesMan){
    Taro.setStorageSync('salesMan',opt.salesMan)
  }else if(opt.q){
    const q = decodeURIComponent(opt.q);
    Taro.setStorageSync('salesMan',queryURLParams(q).salesMan)
  }
  if(opt.path){
    Taro.redirectTo({
      url:opt.path
    })
  }else if(opt.q){
    const q = decodeURIComponent(opt.q);
    if(queryURLParams(q).path){
      Taro.redirectTo({
        url:queryURLParams(q).path
      })
    }
  }
  console.log(opt,Taro.getStorageSync('salesMan'),'opt---------------')
}

export function handleMiniprogram(){
  let ua = navigator.userAgent;
  let value = true
  // 判断是否在微信内
  if (ua.match(/MicroMessenger/g) == "MicroMessenger") {
    value = true
    // wx.miniProgram.getEnv((res) => {
    //   if (res.miniprogram) {
    //     value = true
    //   } else {
    //     value = false
    //   }
    // })
  } else {
    value = false
  }
  return value
}

export function handleCityName(e){
  console.log('handleCityName-----------')
  const {longitude,latitude,cityName} = getUrlParam(location.href)
  let position = {
    longitude,
    latitude,
  }
  if(cityName || longitude){
    Taro.$get('/act/cities/cityName',{cityName:decodeURIComponent(cityName)}).then(res=>{
      let data = {
        longitude,
        latitude,
        cityName:decodeURIComponent(cityName),
        name:decodeURIComponent(cityName),
        cityCode:res.content,
        timeStamp:Date.now()
      }
      position = data
      Taro.setStorageSync('cityInfo',data)
      Taro.eventCenter.trigger('updateLocation')
    })
    if(longitude){
      Taro.setStorageSync('position',position)
    }
  }
}

export {
  debounce,
  throttle,
  toast,
  getUrlParam,
  typeFta,
  deepClone,
  fVailPhone,
  RoundNum,
  format,
  whichPlatform,
  checkSalesMan
}